import React, { FC, useEffect, useState, useRef, useMemo } from 'react'
import { useSearchParams } from 'react-router-dom'
import styles from './common.module.scss'
import QuestionCard from '../../components/QuestionCard'
import { useTitle, useRequest, useDebounceFn } from 'ahooks'
import { Typography, Spin, Empty } from 'antd'
// 搜索组件
import ListSearch from '../../components/ListSearch'

// // 引入获取列表数据的api
// import useLoadQuestionListData from '../../hooks/useLoadQuestionListData'
import { getQuestionListService } from '../../services/question'
import { LIST_DEFAULT_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from '../../constant/index'

const { Title } = Typography

const List: FC = () => {
  useTitle('湘大问卷-我的问卷 ')
  // const [searchParams] = useSearchParams()
  // console.log('keywords', searchParams.get('keywords'))

  // const { data = {}, loading } = useLoadQuestionListData({})
  // const { list = [], total = 0 } = data

  // // 列表数据 和 总数
  // const [list, setList] = useState([])
  // const [total, setTotal] = useState(0)

  // useEffect(() => {
  //   async function load() {
  //     const data = await getQuestionListService()
  //     const { list, total } = data
  //     setList(list)
  //     setTotal(total)
  //   }
  //   load()
  // }, [])

  const [page, setPage] = useState(1) //List内部数据,不在url参数中体现
  const [list, setList] = useState([]) //全部的列表数据,上划加载更多,累计
  const [total, setTotal] = useState(0)
  const [loadStart, setLoadStart] = useState<boolean>(false) //判断是否开始加载

  const haveMoreData = total > list.length //还有没有更多的,没有加载完的数据,true为还有,false为已经加载完毕

  const [searchParams] = useSearchParams() //url参数,虽然没有page,pageSize,但是有keyword
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''

  // keyword变化时重置信息
  useEffect(() => {
    setLoadStart(false), setPage(1), setList([]), setTotal(0)
  }, [keyword])

  // 真正的加载函数
  const { run: load, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        page,
        pageSize: LIST_DEFAULT_PAGE_SIZE,
        keyword,
      })
      return data
    },
    {
      manual: true,
      onSuccess(result) {
        const { list: loadNewList, total = 0 } = result
        setList(list.concat(loadNewList)) //累计
        setTotal(total)
        setPage(page + 1)
        // 加载数据完毕
        setLoadStart(false)
      },
    }
  )

  // 尝试触发加载-节流
  const containerRef = useRef<HTMLDivElement>(null) //获取页面底部加载更多的div元素
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const divELement = containerRef.current
      if (divELement === null) return
      // 判断加载更多的div元素是否漏出到页面的client时空中,如果有说明加载到了底部,需要加载数据
      const domRect = divELement.getBoundingClientRect()
      if (domRect === null) return
      const { bottom } = domRect

      if (bottom <= window.innerHeight) {
        load() //真正加载数据
        // 加载数据ing
        setLoadStart(true)
      }
    },
    { wait: 1000 }
  )

  // 1.当页面加载,或者url参数变化(keyword)变化时,触发加载
  useEffect(() => {
    tryLoadMore()
  }, [searchParams])

  // 2.当页面滚动时,需要尝试加载数据

  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener('scroll', tryLoadMore)
    }

    return () => {
      window.removeEventListener('scroll', tryLoadMore) //加载数据结束后,需要解绑事件，重要!!!
    }
  }, [searchParams, haveMoreData])

  // LoadMore Elem
  const LoadMoreContentElem = useMemo(() => {
    if (!loadStart || loading) return <Spin></Spin>
    if (total === 0) return <Empty description="暂无数据" />
    if (!haveMoreData) return <span>没有更多了.....</span>
    return <span>开始加载下一页</span>
  }, [loadStart, loading, haveMoreData])

  return (
    <>
      {/* header start*/}
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        {/* 搜索框 */}
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      {/* header end*/}
      <div className={styles.container}>
        {/* 问卷列表 */}
        {list.length > 0 &&
          list.map((item: any) => {
            // const { _id, title, isPublished, isStar, answerCount, createdAt } = item
            return <QuestionCard key={item._id} {...item} />
          })}
      </div>
      <div className={styles.footer}>
        <div ref={containerRef}>{LoadMoreContentElem}</div>
      </div>
    </>
  )
}

export default List
